package com.alan.mongodb.dao;

import com.alan.mongodb.bean.Address;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.client.model.Filters;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @Auther: Alan liu
 * @Date: 2018/11/21 18:23
 * @Description: AddressDao
 */
@Component
public class AddressDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    public void indexCityText(){
        DBCollection addressDb = mongoTemplate.getCollection("address");
        // 创建普通索引
        //addressDb.createIndex(new BasicDBObject("city",1));
        // 创建文本索引
        addressDb.createIndex(new BasicDBObject("city","text"));
    }

    public void insert(Address address) {
        //_id 会自动放入到address中
        mongoTemplate.insert(address);
    }

    public List<Address> queryByCity(String city) {
        Query query = new Query();
        Criteria criteria = Criteria.where("city").is(city);
        query.addCriteria(criteria);
        List<Address> list = mongoTemplate.find(query,Address.class);
        return list;
    }

    public List<Address> queryAll() {
        Query query = new Query();
        List<Address> list = mongoTemplate.find(query,Address.class);
        return list;
    }

    public List<Address> queryByCityLike(String city) {
        Query query = new Query();
        Pattern pattern = Pattern.compile("^.*"+city+".*$", Pattern.CASE_INSENSITIVE);
        query.addCriteria(Criteria.where("city").regex(pattern));
        List<Address> list = mongoTemplate.find(query,Address.class);
        return list;
    }
}
